package com.solution.admin.order.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.esotericsoftware.minlog.Log;
import com.solution.admin.company.dao.CompanyInvoiceDao;
import com.solution.admin.company.entity.CompanyInvoiceEntity;
import com.solution.admin.coupon.constants.CouponConstants;
import com.solution.admin.coupon.dao.CouponGetDao;
import com.solution.admin.customer.dao.CompanyDao;
import com.solution.admin.customer.dao.CustomerDao;
import com.solution.admin.customer.entity.CompanyEntity;
import com.solution.admin.customer.entity.CustomerEntity;
import com.solution.admin.finance.wallet.constants.WalletConstants;
import com.solution.admin.finance.wallet.dao.WalletDao;
import com.solution.admin.finance.wallet.dao.WalletFlowDao;
import com.solution.admin.finance.wallet.entity.WalletEntity;
import com.solution.admin.finance.wallet.entity.WalletFlowEntity;
import com.solution.admin.order.constants.OrderConstants;
import com.solution.admin.order.dao.OrderContractDao;
import com.solution.admin.order.dao.OrderDao;
import com.solution.admin.order.dao.OrderDeliveredBillDao;
import com.solution.admin.order.dao.OrderDetailDao;
import com.solution.admin.order.dao.OrderInvoiceDao;
import com.solution.admin.order.dao.OrderLogDao;
import com.solution.admin.order.dao.OrderPayDao;
import com.solution.admin.order.entity.OrderContractEntity;
import com.solution.admin.order.entity.OrderDetailEntity;
import com.solution.admin.order.entity.OrderEntity;
import com.solution.admin.order.entity.OrderInvoiceEntity;
import com.solution.admin.order.entity.OrderLogEntity;
import com.solution.admin.order.entity.OrderPayEntity;
import com.solution.admin.order.entity.OrderStatisticsEntity;
import com.solution.admin.order.service.OrderService;
import com.solution.admin.point.constants.PointConstants;
import com.solution.admin.point.dao.PointDao;
import com.solution.admin.point.dao.PointLogDao;
import com.solution.admin.point.entity.PointEntity;
import com.solution.admin.point.entity.PointLogEntity;
import com.solution.admin.promotion.constants.PromotionConstants;
import com.solution.admin.promotion.entity.PromotionProductEntity;
import com.solution.admin.settings.dao.KeyMapDao;
import com.solution.admin.settings.entity.KeyMapEntity;
import com.solution.common.constants.PublicStatus;
import com.solution.common.dao.BaseDao;
import com.solution.common.exception.BizException;
import com.solution.common.page.PageBean;
import com.solution.common.page.PageParam;
import com.solution.common.service.impl.BaseServiceImpl;
import com.solution.common.utils.string.StringUtil;
import com.solution.pc.order.entity.CustomerOrderStatisticsEntity;
import com.solution.pc.shoppingcart.dao.ShoppingCartDao;
import com.solution.wx.share.dao.ShareInfoDao;
import com.solution.wx.share.entity.ShareInfoEntity;
import com.solution.wx.share.entity.ShareOrderDO;

/**
 * 订单信息service实现层
 * @author lilp
 * @date 2017-09-14 23:35:39
 */
@Service
public class OrderServiceImpl extends BaseServiceImpl<OrderEntity> implements OrderService {

	/**
	 * 订单信息接口
	 */
	@Autowired
	private OrderDao orderDao;
	
	@Autowired
	private OrderDetailDao orderDetailDao;
	
	@Autowired
	private OrderContractDao orderContractDao;
	
	@Autowired
	private OrderPayDao orderPayDao;
	
	@Autowired
	private OrderInvoiceDao orderInvoiceDao;
	
	@Autowired
	private ShoppingCartDao shoppingCardDao;
	
	@Autowired
	private OrderDeliveredBillDao orderDeliveryBillDao;
	
	@Autowired
	private CouponGetDao couponGetDao;
	
	@Autowired
	private PointDao pointDao;
	
	@Autowired
	private PointLogDao pointLogDao;
	
	@Autowired
	private OrderLogDao orderLogDao;
	
	@Autowired
	private ShareInfoDao shareInfoDao;
	
	@Autowired
	private KeyMapDao keyMapDao;

	@Autowired
	private CustomerDao customerDao;
	
	@Autowired
	private CompanyDao companyDao;
	
	@Autowired
	private WalletDao walletDao;
	
	@Autowired
	private WalletFlowDao walletFlowDao;
	
	@Autowired
	private CompanyInvoiceDao companyInvoiceDao;
	
	protected BaseDao<OrderEntity> getDao() {
		return this.orderDao;
	}

	/**
	 * 保存订单信息
	 * @param orderEntity 订单信息实体
	 * @return Long 添加成功订单信息的ID
	 * @author lilp
	 * @date 2017-09-14 23:35:39
	 */
	public long saveOrder(OrderEntity orderEntity) {
		return orderDao.saveOrder(orderEntity);
	}

	/**
	 * 分页查询订单信息
	 * @param pageParam 分页参数
	 * @param paramMap 查询参数
	 * @return PageBean 分页参数和分页数据
	 * @author lilp
	 * @date 2017-09-14 23:35:39
	 */
	@Override
	public PageBean listOrderPage(PageParam pageParam, Map<String, Object> paramMap) {
		return orderDao.listOrderPage(pageParam, paramMap);
	}
	
	/**
	 * 查询发货单列表
	 * @param pageParam
	 * @param paramMap
	 * @return
	 */
	@Override
	public PageBean listOrderDeliveryBillPage(PageParam pageParam, Map<String, Object> paramMap){
		return orderDao.listOrderDeliveryBillPage(pageParam, paramMap);
	}
	
	/**
	 * 分页查询待确认的付款凭证列表
	 * @param pageParam
	 * @param paramMap
	 * @return
	 */
	@Override
	public PageBean listConfirmPayOrderPage(PageParam pageParam, Map<String, Object> paramMap){
		return orderDao.listConfirmPayOrderPage(pageParam, paramMap);
	}
	
	/**
	 * 根据ID查询用户信息
	 * @param id 用户id
	 * @return orderEntity 用户对象
	 * @author lilp
	 * @date 2017-09-14 23:35:39
	 */
	public OrderEntity getOrderById(Long id) {
		return orderDao.getById(id.longValue());
	}

	/**
	 * 更新用户
	 * @param orderEntity 用户实体
	 * @return Long 更新是否成功，>1代表更新成功
	 * @author lilp
	 * @date 2017-09-14 23:35:39
	 */
	@Override
	public int updateOrder(OrderEntity orderEntity) {
		return orderDao.updateOrder(orderEntity);
	}
	
	
	/**
	 * 根据条件查询订单信息
	 * @param param
	 * @return 数据列表
	 * @author lilp
	 * @date 2017-09-14 23:35:39
	 */
	@Override
	public List<OrderEntity> listOrder( Map<String, Object> param){
		return  orderDao.listOrder(param);
	}
	
	/**
	 * 删除订单信息
	 * @param 
	 * @return int 返回删除记录条数
	 * @author lilp
	 * @date 2017-09-14 23:35:39
	 */
	public int deleteOrderById(long id){
		return  orderDao.deleteById(id);
	}
	
	/**
	 * 订单调价操作
	 * @param param
	 * @return
	 * @author lilp
	 * @date 2017-09-14 23:35:39
	 */
	public int adjustOrderPrice(Map<String, Object> param){
		
		
		//待更新的订单商品详情列表（更新调价字段）
		List<OrderDetailEntity> orderDetailList = new ArrayList<OrderDetailEntity>();
		
		//查询订单原始数据
		List<OrderEntity>  orderList = orderDao.listOrder(param);
		OrderEntity order = null;
		if(orderList !=null && orderList.size() > 0){
			order = orderList.get(0);
			// 取订单详情
			List<OrderDetailEntity> productList = JSONArray.parseArray("[" + order.getProductDetail() + "]",OrderDetailEntity.class);
			BigDecimal oldTotalProductPrice = new BigDecimal(0);
			if (productList != null && productList.size() > 0) {
				for (OrderDetailEntity product : productList) {
					// 累计商品总金额 如果有商品调价，则按调价后价格，否则按商品原价
					oldTotalProductPrice = oldTotalProductPrice.add((product.getProductAdjustPrice() == null ? product.getProductPrice() : product.getProductAdjustPrice())
							.multiply(new BigDecimal(product.getBuyNum())));
				}
			}
			
			// 修改订单应付金额  运费  商品调价总计  订单调价
			BigDecimal deliveryFeeMoney = new BigDecimal(String.valueOf(param.get("deliveryFeeMoney")));
			BigDecimal adjustOrderMoney = new BigDecimal(String.valueOf(param.get("orderAdjustMoney")));
			
			// 重新计算商品调价金额
			String[] ids = ((String)param.get("ids")).split(",");
			String[] buyNums = ((String)param.get("buyNums")).split(",");
			String[] productAdjustPrices = ((String)param.get("produtAdjustPrice")).split(",");
			String[] productPrices = ((String)param.get("produtPrice")).split(",");
			BigDecimal totalProductAdjustPrice = new BigDecimal(0);
			BigDecimal totalProductMoney = new BigDecimal(0);
			for(int i = 0 ; i < buyNums.length; i++){
				// 商品调价差额
				totalProductAdjustPrice = totalProductAdjustPrice.add(
						new BigDecimal(buyNums[i]).multiply(new BigDecimal(productPrices[i]).subtract(new BigDecimal(productAdjustPrices[i]))));
				// 商品总价
				totalProductMoney = totalProductMoney.add(new BigDecimal(buyNums[i]).multiply(new BigDecimal(productAdjustPrices[i])));
				OrderDetailEntity orderDetail = new OrderDetailEntity();
				orderDetail.setId(Long.parseLong(ids[i]));
				orderDetail.setProductAdjustPrice(new BigDecimal(productAdjustPrices[i]));
				orderDetailList.add(orderDetail);
			}
			
			BigDecimal newRealPayMoney  = totalProductMoney.subtract(order.getPointsMoney()).subtract(order.getCouponMoney()).subtract(order.getPromotionDiscountMoney());
			// 重新计算应付金额   = 调整后差价 + 订单调价金额 + 物流运费
			BigDecimal realPayMoney = newRealPayMoney.add(adjustOrderMoney).add(deliveryFeeMoney);
			
			// 运费
			order.setDeliveryFeeMoney(deliveryFeeMoney);
			// 订单调价
			order.setAdjustOrderMoney(adjustOrderMoney);
			// 商品调价
			order.setAdjustProductMoney(totalProductAdjustPrice);
			// 应付金额
			order.setRealPayMoney(realPayMoney);
			// 已调价
			order.setAdjustPriceFlag("3");
			// 修改订单
			orderDao.adjustOrderPrice(order);
		}
		
		int result = 0;
		// 修改订单商品详情 调价
		if(orderDetailList.size() > 0 ){
			result = orderDetailDao.batchAdjustOrderProductPrice(orderDetailList);
		}
		return result;
	}
	
	
	/**
	 * 审核订单
	 * @param param
	 * @return
	 */
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor=Exception.class)
	public int approveOrder(Map<String, Object> param){
		// 确认合同
		int result1 = 0;
		try {
			int result = orderDao.updateOrderApproveResult(param);
			String approveResult = (String)param.get("approveResult");
			String confirmType = (String)param.get("confirmType");
			result1 = result - 1;
			if("1".equals(confirmType)){
				// 确认合同
				if(OrderConstants.ORDER_APPROVE_STATUS.PASS.getCode().equals(approveResult)){
					param.put("confirmStatus", OrderConstants.ORDER_CONTRACT_STATUS.CONFIRMED.getCode());
				}else{
					param.put("confirmStatus", OrderConstants.ORDER_CONTRACT_STATUS.CONFIRMED_NOT_PASS.getCode());
				}
				result1 = orderContractDao.updateOrderContractStatus(param);
			}else{
				// 确认凭证
				if(OrderConstants.ORDER_APPROVE_STATUS.PASS.getCode().equals(approveResult)){
					param.put("confirmStatus", OrderConstants.ORDER_PAY_CONFIRM_STATUS.CONFIRMED.getCode());
				}else{
					param.put("confirmStatus", OrderConstants.ORDER_PAY_CONFIRM_STATUS.CONFIRMED_NOT_PASS.getCode());
				}
				result1 = orderPayDao.updateOrderPayStatus(param);
			}
			//记录日志
			if (param.containsKey("orderLogEntity") && param.get("orderLogEntity") != null) {
				OrderLogEntity orderLog = (OrderLogEntity)param.get("orderLogEntity");
				orderLogDao.saveOrderLog(orderLog);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new BizException("订单审核失败！");
		}
		return result1;
	}
	
	/**
	 * 取消订单
	 * @param param
	 * @return
	 */
	@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
	public int cancelOrder(Map<String, Object> param){
		// 更新订单状态为取消状态
		int result = 0;
		result = orderDao.cancelOrder(param);
		
		// 检查订单是否有使用积分、和优惠券; 如果有退回
		Map<String, Object> tparam = new HashMap<String, Object>();
		tparam.put("orderCode", param.get("orderCode"));
		List<OrderEntity> orderList = orderDao.listOrder(tparam);
		OrderEntity orderEntity = orderList.get(0);
		// 如果有使用积分，退回用户积分
		if(orderEntity.getUserPoints() != null && orderEntity.getUserPoints().intValue() > 0){
			// 查询当前客户积分
			PointEntity userPointAccount = pointDao.getPointByCustomerId(orderEntity.getCustomerId());
			
			// 扣除积分，减少积分余额，插入积分消费记录
			PointEntity point  = new PointEntity();
			point.setCustomerId(orderEntity.getCustomerId());
			// 操作 -操作
			point.setPoint(orderEntity.getUserPoints());
			point.setModifier(orderEntity.getCreater());
			pointDao.updateCustomerPoint(point);
			
			// 插入积分消息记录(撤单退回)
			PointLogEntity  pointLog = new PointLogEntity();
			pointLog.setCustomerId(orderEntity.getCustomerId());
			pointLog.setOperateType(PointConstants.PointOperateType.OPT_CANCAL_ORDER.getCode());
			pointLog.setOperateFlag(PointConstants.PointOperateFlag.FLAG_ADD.getId());
			pointLog.setOperatePoint(orderEntity.getUserPoints() );
			pointLog.setBeforePoint(userPointAccount.getPoint());
			pointLog.setAfterPoint(userPointAccount.getPoint().subtract(orderEntity.getUserPoints()));
			pointLog.setAdjustReason("撤单退回积分");
			pointLog.setBillCode(orderEntity.getOrderCode());
			pointLog.setBillTime(orderEntity.getOrderTime());
			pointLog.setOperateUser(orderEntity.getCreater());
			pointLogDao.insert(pointLog);
		}
		
		// 如果有使用优惠券，退回优惠券
		if(StringUtil.isNotEmpty(orderEntity.getCouponIds())){
			String[] couponIdArr = orderEntity.getCouponIds().split(",");
			Map<String, Object> tmpPraram = new HashMap<String, Object>();
			for (String couponId : couponIdArr) {
				// 把使用使用标记、和单据号清空掉
				tmpPraram.put("isUsed", CouponConstants.IsUsed.UN_USED);
				tmpPraram.put("id", Long.parseLong(couponId));
				couponGetDao.updateUserCouponStatus(tmpPraram);
			}
		}
		return result;
	}
	
	/**
	 * 确认订单合同
	 * @param param
	 * @return
	 */
	public int confirmOrderContract(Map<String, Object> param){
		// 修改订单状态
		int result = orderDao.updateOrderContractStatus(param);
		// 修改订单合同确认状态
		result += orderContractDao.updateOrderContractStatus(param);
		return result;
	}
	
	/**
	 * 提交订单
	 * @param param
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "unused" })
	@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
	public int commitOrder(Map<String, Object> param){
		// 保存订单基础信息
		OrderEntity orderEntity = (OrderEntity)param.get("orderInfo");
		long orderId = orderDao.saveOrder(orderEntity);
		
		// 保存订单详情
		List<OrderDetailEntity> orderDetailList = (List<OrderDetailEntity>)param.get("orderDetailList");
		int resultOrderDetail = orderDetailDao.saveOrderDetailBatch(orderDetailList);
		
		// 保存发票信息
		OrderInvoiceEntity invoice = (OrderInvoiceEntity)param.get("invoice");
		long invoiceId =  orderInvoiceDao.saveOrderInvoice(invoice);
		// 保存最后一次发票信息
		saveCustomerLastInvoice(orderEntity, invoice);
		
		// 如果订单使用到积分将积分扣减，记录积分消费日志
		if(orderEntity.getUserPoints() != null && orderEntity.getUserPoints().intValue() > 0){
			
			// 查询当前客户积分
			PointEntity userPointAccount = pointDao.getPointByCustomerId(orderEntity.getCustomerId());
			
			// 扣除积分，减少积分余额，插入积分消费记录
			PointEntity point  = new PointEntity();
			point.setCustomerId(orderEntity.getCustomerId());
			// 扣减操作 -操作
			point.setPoint(orderEntity.getUserPoints().multiply(new BigDecimal(-1)));
			point.setModifier(orderEntity.getCreater());
			pointDao.updateCustomerPoint(point);
			
			// 插入积分消息记录
			PointLogEntity  pointLog = new PointLogEntity();
			pointLog.setCustomerId(orderEntity.getCustomerId());
			pointLog.setOperateType(PointConstants.PointOperateType.OPT_BUY.getCode());
			pointLog.setOperateFlag(PointConstants.PointOperateFlag.FLAG_MINUS.getId());
			pointLog.setOperatePoint(orderEntity.getUserPoints() );
			pointLog.setBeforePoint(userPointAccount.getPoint());
			pointLog.setAfterPoint(userPointAccount.getPoint().subtract(orderEntity.getUserPoints()));
			pointLog.setAdjustReason("下单消费");
			pointLog.setBillCode(orderEntity.getOrderCode());
			pointLog.setBillTime(orderEntity.getOrderTime());
			pointLog.setOperateUser(orderEntity.getCreater());
			pointLogDao.insert(pointLog);
			
			
		}
		// 修改已使用优惠券的状态 
		if(StringUtil.isNotEmpty(orderEntity.getCouponIds())){
			String[] couponArr = orderEntity.getCouponIds().split(",");
			Map<String, Object> tparam = new HashMap<String, Object>();
			// 一般限制最多使用一张优惠券
			for (String couponId : couponArr) {
				tparam.put("id", Long.parseLong(couponId));
				tparam.put("isUsed", CouponConstants.IsUsed.USED);
				tparam.put("billCode", orderEntity.getOrderCode());
				couponGetDao.updateUserCouponStatus(tparam);
			}
		}
		
		//清空购物车已经结算的商品
		List<String> shoppingcartIds = (List<String>)param.get("shoppingcartIds");
		param.put("ids", shoppingcartIds);
		int resultDelShoppingCart =	shoppingCardDao.deleteShoppingCartProduct(param);
		
		//记录日志
		if (param.containsKey("orderLogEntity") && param.get("orderLogEntity") != null) {
			OrderLogEntity orderLog = (OrderLogEntity)param.get("orderLogEntity");
			orderLogDao.saveOrderLog(orderLog);			
		}
		
		// 处理订单分享记录
		Object shareLog = (Map<String, Object>) param.get("shareInfo");
		if(shareLog != null){
			Map<String, Object> shareLogParam = (Map<String, Object>) shareLog;
			shareInfoDao.saveShareOrder(shareLogParam);
		}
		return resultDelShoppingCart > 0 ? 1 : 0;
	}
	
	
	/**
	 * 保存客户最近一次下单的发票信息
	 * @param order
	 * @param invoice
	 */
	private void saveCustomerLastInvoice(OrderEntity order,  OrderInvoiceEntity invoice){
		CompanyInvoiceEntity lastInvoice = new CompanyInvoiceEntity();
		lastInvoice.setCustomerId(order.getCustomerId());
		lastInvoice.setInvoiceType(order.getInvoiceType());
		lastInvoice.setCompanyName(invoice.getCompnayName());
		lastInvoice.setTaxNo(invoice.getTaxNo());
		if(OrderConstants.ORDER_INVOICE_TYPE.ADDED.getCode().equals(order.getInvoiceType())){
			lastInvoice.setRegisteAddress(invoice.getRegisteAddress());
			lastInvoice.setRegistePhone(invoice.getRegistePhone());
			lastInvoice.setBankAccount(invoice.getBankAccount());
			lastInvoice.setOpenBankName(invoice.getOpenBankName());
		}
		// 查询是否存在最近一次开票信息
		CompanyInvoiceEntity existsLastInvoice = companyInvoiceDao.getLastInvoice(order.getCustomerId());
		if(existsLastInvoice != null){
			lastInvoice.setId(existsLastInvoice.getId());
			companyInvoiceDao.updateLastInvoice(lastInvoice);
		}else{
			companyInvoiceDao.saveLsatInvoice(lastInvoice);
		}
	}
	
	/**
	 * 更新订单状态
	 * @param payParam
	 * @return
	 */
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public int updateOrderStatus(Map<String, Object> payParam){
		try {
			// 插入支付记录
			OrderPayEntity orderPay = (OrderPayEntity)payParam.get("orderPay");
			long orderPayId = orderPayDao.insert(orderPay);

			//记录日志
			if (payParam.containsKey("orderLogEntity") && payParam.get("orderLogEntity") != null) {			
				OrderLogEntity orderLog = (OrderLogEntity)payParam.get("orderLogEntity");
				orderLogDao.saveOrderLog(orderLog);
			}
			if(orderPayId > 0){
				int result = orderDao.updateOrderStatus(payParam);
				return result;
			}else{
				return 0;
			}
		} catch (Exception e) {
			// 抛出异常回滚事务
			throw new BizException(e);
		}
	}
	
	/**
	 * 查询首页客户订单数量统计
	 * @param param
	 * @return
	 * @author lilp
	 */
	public List<CustomerOrderStatisticsEntity> listCustomerOrderStatistics(Map<String, Object> param){
		return orderDao.listCustomerOrderStatistics(param);
	}
	
	/**
	 * 查询我的订单
	 * @param pageParam
	 * @param paramMap
	 * @return
	 * @author llp
	 */
	public PageBean listMyOrderPage(PageParam pageParam,Map<String, Object> paramMap){
		return orderDao.listMyOrderPage(pageParam, paramMap);
	}
	
	/**
	 * 全部签收订单
	 * @param param
	 * @return
	 * @author lilp
	 */
	@Transactional(propagation = Propagation.REQUIRED,rollbackFor=Exception.class)
	public int signFullOrder(Map<String, Object> param){
		// 更新订单下的所有发货单为已签收
		int result = 0;
		try {
			result = orderDeliveryBillDao.updateDeliveryBillStatus(param);
			
			// 签收完成后，判断是否订单完成，若完成，将订单参加活动赠送优惠券和积分发放到客户账户（实时）
			// 查询订单信息
			Map<String, Object> tparam = new HashMap<String, Object>();
			tparam.put("orderCode", param.get("orderCode"));
			List<OrderEntity> orderList = orderDao.listOrder(param);
			OrderEntity order = orderList.get(0);
			
			// 查询订单详情
			List<OrderDetailEntity>  detailList = orderDetailDao.listOrderDetail(param);
			// 判断付款方式
			if(OrderConstants.ORDER_PAY_MODEL.PAY_NOW.getCode().equals(order.getPayModel())){
				// 立即付款
				// 更新订单状态为已完成状态
				param.put("orderStatus", OrderConstants.ORDER_STATUS.FINISHED.getCode());
				param.put("finishTime", new Date());
				result += orderDao.updateOrderStatus(param);
				// 发放活动中的优惠券和积分
				handleCouponPoints(order,detailList);
				// 处理客户订单推荐积分和奖金返现(立即付款的订单在签收时返现推荐人的奖励和积分)
				handleReferrerPointsAndRewards(order, detailList);
			}else{
				// 货到付款
				// 更新订单状态为待付款状态
				param.put("orderStatus", OrderConstants.ORDER_STATUS.WAIT_TO_PAY.getCode());
				result += orderDao.updateOrderStatus(param);
			}
						
			//记录日志
			if (param.containsKey("orderLogEntity") && param.get("orderLogEntity") != null) {			
				OrderLogEntity orderLog = (OrderLogEntity)param.get("orderLogEntity");
				orderLogDao.saveOrderLog(orderLog);
			}
		} catch (Exception e) {
			// 捕获抛出异常，用于回滚事务
			throw new BizException("订单签收失败,订单号："+param.get("orderCode"), e);
		}
		return result;
	}
	
	/**
	 * 签收发货单(部分签收)
	 * @param param
	 * @return
	 */
	@Transactional(propagation = Propagation.REQUIRED,rollbackFor=Exception.class)
	public int signHalfOrder(Map<String, Object> param){
		// 更新发货单状态为已签收
		int result;
		try {
			result = orderDeliveryBillDao.updateDeliveryBillSignInfo(param);
			// 判断订单购物数量和签收发货数量是否一致，一致则更新订单状态 
			int notSignCount = orderDeliveryBillDao.selectOrderProductAllDeliveryed(param);
			// 0 代表所有商品都已经签收，将订单状态 修改为已完成
			if(notSignCount  == 0){
				
				// 签收完成后，判断是否订单完成，若完成，将订单参加活动赠送优惠券和积分发放到客户账户（实时）
				// 查询订单信息
				Map<String, Object> tparam = new HashMap<String, Object>();
				tparam.put("orderCode", param.get("orderCode"));
				List<OrderEntity> orderList = orderDao.listOrder(param);
				OrderEntity order = orderList.get(0);
				// 查询订单详情
				List<OrderDetailEntity>  detailList = orderDetailDao.listOrderDetail(param);
				
				// 判断付款方式
				if(OrderConstants.ORDER_PAY_MODEL.PAY_NOW.getCode().equals(order.getPayModel())){
					// 立即付款
					// 更新订单状态为已完成状态
					param.put("orderStatus", OrderConstants.ORDER_STATUS.FINISHED.getCode());
					param.put("finishTime", new Date());
					orderDao.updateOrderStatus(param);
					// 发放活动中的优惠券和积分
					handleCouponPoints(order, detailList);
					// 处理客户订单推荐积分和奖金返现(立即付款的订单在签收时返现推荐人的奖励和积分)
					handleReferrerPointsAndRewards(order, detailList);
				}else{
					// 货到付款
					// 更新订单状态为待付款状态
					param.put("orderStatus", OrderConstants.ORDER_STATUS.WAIT_TO_PAY.getCode());
					orderDao.updateOrderStatus(param);
				}
			}

			//记录日志
			if (param.containsKey("orderLogEntity") && param.get("orderLogEntity") != null) {
				OrderLogEntity orderLog = (OrderLogEntity)param.get("orderLogEntity");
				if (notSignCount != 0) {
					orderLog.setLogContent("订单部分签收");
				}
				orderLogDao.saveOrderLog(orderLog);
			}
		} catch (Exception e) {
			// 捕获抛出异常，用于回滚事务
			throw new BizException("订单部分签收失败,订单号："+param.get("orderCode"), e);
		}
		return result;
	}
	
	/**
	 * 处理订单完成后，发送赠送的优惠券和积分
	 * @param orderCode
	 */
	private void handleCouponPoints(OrderEntity order , List<OrderDetailEntity>  detailList){
		// 如果是立即支付，赠送积分
		// 循环订单商品，计算每个商品对应的积分，为客户增加积分
		// 包括两部分积分  1 商品本身送的积分  商品活动赠送的积分，和优惠券
		String orderCode = order.getOrderCode();
		long customerId = order.getCustomerId();
		// 订单商品积分（不同于活动赠送的积分）
		BigDecimal totalProductPoints = new BigDecimal(0);
		for (OrderDetailEntity detail : detailList) {
			// 活动的结果
			if(StringUtil.isNotEmpty(detail.getPromotionResult())){
				List<PromotionProductEntity> promotionList = JSONArray.parseArray(detail.getPromotionResult(), PromotionProductEntity.class);
				if(promotionList != null && promotionList.size() > 0){
					for (PromotionProductEntity promotion : promotionList) {
						// 判断活动中的赠送优惠券、积分
						if(PromotionConstants.PROMOTION_TYPE.GIFT.getName().equals(promotion.getPromotionTypeName())){
							Map<String, Object> tparam = new HashMap<String, Object>();
							if(PromotionConstants.PROMOTION_GIFT_TYPE.COUPON.getCode().equals(promotion.getGiftType())){
								// 发放赠送优惠券（实时到账）
								tparam.put("couponId", promotion.getCouponId());
								tparam.put("customerId", order.getCustomerId());
								couponGetDao.sendPromotionCoupon(tparam);
							}else if(PromotionConstants.PROMOTION_GIFT_TYPE.POINTS.getCode().equals(promotion.getGiftType())){
								// 发放赠送积分(实时到账)
								//tparam.put("customerId", customerId);
								//tparam.put("points", promotion.getPoints());
								
								/**
								 * 更新客户积分 要在 “插入积分流水日志”之后<br>
								 * 因为积分日志有个字段是“操作前积分值”
								 * */
								// 获取之前的 客户积分余额
								PointEntity pointAccount = pointDao.getPointByCustomerId(customerId);
								
								// 1、插入积分流水日志
								PointLogEntity pointLog = new PointLogEntity();
								pointLog.setCustomerId(customerId);
								pointLog.setOperateType(PointConstants.PointOperateType.OPT_PROMOTION_GIFT.getCode());
								pointLog.setOperateFlag(PointConstants.PointOperateFlag.FLAG_ADD.getId());
								pointLog.setOperatePoint(promotion.getPoints());
								pointLog.setBeforePoint(pointAccount.getPoint());
								pointLog.setAfterPoint(pointAccount.getPoint().add(promotion.getPoints()));
								pointLog.setAdjustReason("活动赠送");
								pointLog.setBillCode(orderCode);
								pointLog.setBillTime(order.getOrderTime());
								pointLog.setOperateTime(new Date());
								pointLog.setOperateUser(order.getCustomerName());
								pointLogDao.insert(pointLog);
								// 2.更新积分（）
								PointEntity pointEntity = new PointEntity();
								pointEntity.setCustomerId(customerId);
								pointEntity.setModifier("");
								pointEntity.setPoint(promotion.getPoints());
								pointDao.updateCustomerPoint(pointEntity);
							}
						}
					}
				}
			}
			
			// 订单的商品积分
			BigDecimal subTotalItemMoney = (detail.getProductAdjustPrice() != null ? detail.getProductAdjustPrice() : detail.getProductPrice()).multiply(new BigDecimal(detail.getBuyNum()));
			BigDecimal itemProductPoints = subTotalItemMoney.multiply(detail.getProductPointRatio()).multiply(detail.getCustomerPointRatio())
					.divide(new BigDecimal(1000F),1);
			totalProductPoints = totalProductPoints.add(itemProductPoints);
		}
		
		/**
		 * 货到付款的订单不送商品积分
		 */
		boolean sendPoints = OrderConstants.ORDER_PAY_MODEL.PAY_NOW.getCode().equals(order.getPayModel())?true:false;
		if(totalProductPoints.floatValue() > 0 && sendPoints){
			// 插入商品积分记录
			// 查询客户当前积分余额
			PointEntity pointAccount = pointDao.getPointByCustomerId(customerId);
			// 插入积分流水日志
			PointLogEntity pointLog = new PointLogEntity();
			pointLog.setCustomerId(customerId);
			pointLog.setOperateType(PointConstants.PointOperateType.OPT_MONTH_ORDER.getCode());
			pointLog.setOperateFlag(PointConstants.PointOperateFlag.FLAG_ADD.getId());
			pointLog.setOperatePoint(totalProductPoints);
			pointLog.setBeforePoint(pointAccount.getPoint());
			pointLog.setAfterPoint(pointAccount.getPoint().add(totalProductPoints));
			pointLog.setAdjustReason("下单商品预赠（非实时到账）积分，后台确认后到账！");
			pointLog.setBillCode(orderCode);
			pointLog.setBillTime(order.getOrderTime());
			pointLog.setOperateTime(new Date());
			pointLog.setOperateUser(order.getCustomerName());
			pointLogDao.insert(pointLog);
		}
	}
	
	
	/**
	 * 处理推荐人的积分和返现奖金
	 * @param order
	 */
	private void handleReferrerPointsAndRewards(OrderEntity order, List<OrderDetailEntity> detailList){
		// 查询订单是否是分享订单
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("orderCode", order.getOrderCode());
		List<ShareOrderDO>  shareList = shareInfoDao.listShareOrder(param);
		if(shareList != null && shareList.size() ==1){
			ShareOrderDO shareOrderDO = shareList.get(0);
			Long shareId = shareOrderDO.getShareId();
			// 查询分享信息
			ShareInfoEntity shareInfoEntity = shareInfoDao.getById(shareId);
			// 分享人
			CustomerEntity shareCustomer = customerDao.getById(shareInfoEntity.getShareUserId());
			// 下单客户 
			CustomerEntity orderCustomer = customerDao.getById(order.getCustomerId());
			if(shareInfoEntity != null && shareInfoEntity.getShareUserId() != null){
				// 如果是自己分享的连接，自己购买(分享人 == 下单人)
				if(shareCustomer.getId().equals(orderCustomer.getId())){
					// 不给自己返现金额 ，但要计算上线积分
					// 计算需要返给上线的积分
					calculateReferralPoints(order ,detailList);
				}else if(shareCustomer.getInvitationCode().equals(orderCustomer.getParentInvitationCode())){
					// 如果只上下级推荐关系，只送积分, 下单客户的推荐码 = 分享客户的推荐码
					calculateReferralPoints(order ,detailList);
				}else{
					// 不是上下级关系 ，计算客户返现金额 
					calculateReferralRewards(shareInfoEntity , order);
				}
			}
		}else if(shareList.size() > 1){
			throw new BizException("同一个订单关联了两条分享记录,订单号："+order.getOrderCode());
		}else{
			// 计算需要返给上线的积分
			calculateReferralPoints(order, detailList);
		}
	}
	
	
	/**
	 * 处理推荐客户下单返现金额
	 * @param shareInfoEntity
	 * @param order
	 */
	private void calculateReferralRewards(ShareInfoEntity shareInfoEntity , OrderEntity order){
		// 返回奖金 = 订单实收金额  * 奖金系数 * 客户推客系数
		// 查询奖金系数
		
		KeyMapEntity rewardRatioEntity = keyMapDao.getByType("rewardsRatio");
		BigDecimal rewardsRatio = new BigDecimal(Double.parseDouble(rewardRatioEntity.getKeyValue()));
		
		// 查询客户推客系统(这里查询是推荐人的推客系数)
		CustomerEntity shareUser = customerDao.getById(shareInfoEntity.getShareUserId());
		CompanyEntity companyEntity = companyDao.getById(shareUser.getCompanyId());
		BigDecimal referralsRatio = companyEntity.getReferralsRatio();
		
		BigDecimal totalReward = order.getRealPayMoney().multiply(rewardsRatio).multiply(referralsRatio);
		// 记录奖金流水,增加财务账户余额
		if(totalReward.intValue() > 0){
			Long customerId = shareInfoEntity.getShareUserId();
			Map<String, Object> wparam = new HashMap<String, Object>();
			wparam.put("customerId", customerId);
			List<WalletEntity> walletList = walletDao.listBy(wparam);
			WalletEntity walletEntity = null;
			if(walletList != null && walletList.size() == 1){
				walletEntity = walletList.get(0);
			}else if(walletList.size() > 1){
				throw new BizException("客户出现多个相同的财富账户,客户号:" + customerId);
			}
			if(walletEntity != null) {
				// 插入财务流水记录
				
				WalletFlowEntity flow = new WalletFlowEntity();
				flow.setCustomerId(customerId);
				flow.setFlowType(WalletConstants.WALLET_FLOW_TYPE.IN.getCode());
				flow.setPayType(WalletConstants.WALLET_PAY_TYPE.IN.getCode());
				flow.setInMoney(totalReward);
				flow.setBalanceMoney(walletEntity.getGetableMoney().add(totalReward));
				flow.setPayTime(new Date());
				flow.setBillCode(order.getOrderCode());
				flow.setIntro("推荐客户下单返现");
				walletFlowDao.insert(flow);
				
				// 更新财务账户余额 getableMoney 是余额
				walletEntity.setTotalMoney(walletEntity.getTotalMoney().add(totalReward));
				walletEntity.setGetableMoney(walletEntity.getGetableMoney().add(totalReward));
				walletDao.update(walletEntity);
			}
		}
	}
	
	/**
	 * 计算推荐人获取的积分
	 * @param order
	 */
	private void calculateReferralPoints(OrderEntity order, List<OrderDetailEntity> detailList){
		// 判断下单人是否有上线，返现积分
		// 查询当前下单客户的上线
		CustomerEntity customer = customerDao.getById(order.getCustomerId());
		// 有上线
		CustomerEntity parentCustomer = null;
		if (StringUtil.isNotEmpty(customer.getParentInvitationCode())) {
			Map<String, Object> cparam = new HashMap<String, Object>();
			cparam.put("invitationCode", customer.getParentInvitationCode());
			List<CustomerEntity> customerList = customerDao.listCustomer(cparam);
			if (customerList != null && customerList.size() == 1) {
				parentCustomer = customerList.get(0);
			} else if (customerList.size() > 1) {
				throw new BizException("多个客户推荐码重复" + customer.getParentInvitationCode());
			}
		}
		if (parentCustomer != null) {

			// 订单商品积分（不同于活动赠送的积分）
			BigDecimal returnPoints = calculateOrderReferralPoints(order, detailList);
			
			// 1、插入积分流水日志
			// 获取之前的 客户积分余额
			PointEntity pointAccount = pointDao.getPointByCustomerId(parentCustomer.getId());
			PointLogEntity pointLog = new PointLogEntity();
			pointLog.setCustomerId(parentCustomer.getId());
			pointLog.setOperateType(PointConstants.PointOperateType.OPT_REFERRAL_RETURN.getCode());
			pointLog.setOperateFlag(PointConstants.PointOperateFlag.FLAG_ADD.getId());
			pointLog.setOperatePoint(returnPoints);
			pointLog.setBeforePoint(pointAccount.getPoint());
			pointLog.setAfterPoint(pointAccount.getPoint().add(returnPoints));
			pointLog.setAdjustReason("推荐下单返现");
			pointLog.setBillCode(order.getOrderCode());
			pointLog.setBillTime(order.getOrderTime());
			pointLog.setOperateTime(new Date());
			pointLog.setOperateUser(order.getCustomerName());
			pointLogDao.insert(pointLog);
			// 2.更新积分（实时到账）
			PointEntity pointEntity = new PointEntity();
			pointEntity.setCustomerId(parentCustomer.getId());
			pointEntity.setModifier("");
			pointEntity.setPoint(returnPoints);
			pointDao.updateCustomerPoint(pointEntity);
		}
	}
	
	
	/**
	 * 计算推荐客户下单返现的商品积分，如：客户获取商品积分的30% 返现给推荐人
	 * @param order
	 * @param detailList
	 * @return
	 */
	public BigDecimal calculateOrderReferralPoints(OrderEntity order, List<OrderDetailEntity> detailList){
		// 订单商品积分（不同于活动赠送的积分）
		BigDecimal totalProductPoints = new BigDecimal(0);
		for (OrderDetailEntity detail : detailList) {
			// 订单的商品积分
			BigDecimal subTotalItemMoney = (detail.getProductAdjustPrice() != null ? detail.getProductAdjustPrice() : detail.getProductPrice()).multiply(new BigDecimal(detail.getBuyNum()));
			BigDecimal itemProductPoints = subTotalItemMoney.subtract(detail.getProductPointRatio()).multiply(detail.getCustomerPointRatio())
					.divide(new BigDecimal(1000));;
			totalProductPoints = totalProductPoints.add(itemProductPoints);
		}
		
		// 查询推荐客户下单积分返现比例
		KeyMapEntity rewardRatioEntity = keyMapDao.getByType("referralPointRatio");
		BigDecimal referralPointRatio = new BigDecimal(Double.parseDouble(rewardRatioEntity.getKeyValue()));
		
		// 计算返现积分 = 客户下单积分 * 返回积分比例
		BigDecimal returnPoints = totalProductPoints.multiply(referralPointRatio);
		return returnPoints;
	}
	
	

	/**
	 * 根据订单编号获取订单
	 * @param orderCode
	 * @return
	 * @author xkl
	 * @date 2017年11月21日 下午4:28:58
	 */
	@Override
	public OrderEntity getOrderByCode(String orderCode) {
		return orderDao.getOrderByCode(orderCode);
	}

	/**
	 * 完成订单支付
	 * @param order
	 * @param orderPay
	 * @return
	 * @author xkl
	 * @date 2017年11月22日 下午3:48:29
	 */
	@Override
	@Transactional
	public int commitOrderPay(OrderEntity order, OrderPayEntity orderPay, OrderLogEntity orderLog) {
		int result = 0; 
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("payType", order.getPayType());
		param.put("orderCode", order.getOrderCode());
		param.put("payTime", order.getPayTime());
		param.put("modifier", order.getModifier());
		param.put("payStatus", OrderConstants.ORDER_PAY_STATUS.PAYED.getCode());
		if(OrderConstants.ORDER_PAY_MODEL.PAY_NOW.getCode().equals(order.getPayModel())){
			// 立即付款 更新订单状态、付款状态、付款时间
			param.put("orderStatus", OrderConstants.ORDER_STATUS.WAIT_TO_APPROVE.getCode());
		}else if(OrderConstants.ORDER_PAY_MODEL.PAY_DELIVERY.getCode().equals(order.getPayModel())){
			// 货到付款 订单状态修改为待核销
			param.put("orderStatus", OrderConstants.ORDER_STATUS.WAIT_TO_CHECK.getCode());
		}
		result = orderDao.updateOrderStatus(param);
		
		// 逻辑删除已存在支付记录，主要是为了处理订单审核驳回后，客户重新支付的情况 
		orderPayDao.deleteOrderOldPayRecord(param);
		
		result += orderPayDao.insert(orderPay);
		//记录日志
		if (null != orderLog) {
			orderLogDao.saveOrderLog(orderLog);
		}
		
		return result;
	}
	
	/**
	 * 上传订单合同
	 * @param param
	 * @return
	 * @author llp
	 */
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
	public int uploadOrderContract(Map<String, Object> param){
		int result = 0;
		
		String approveResult = (String)param.get("approveResult");
		if(OrderConstants.ORDER_APPROVE_STATUS.NOT_PASS.getCode().equals(approveResult)){
			// 重新上传合同,修改合同，追加附件
			OrderContractEntity  contract = new OrderContractEntity();
			contract.setId(Long.parseLong((String)param.get("contractId")));
			contract.setOrderCode((String)param.get("orderCode"));
			contract.setFilePath((String)param.get("contractImagePath"));
			contract.setConfirmStatus(OrderConstants.ORDER_CONTRACT_STATUS.NOT_CONFIRM.getCode());
			contract.setIntro((String)param.get("intro"));
			contract.setCreater((String)param.get("creater"));
			contract.setIsDelete(PublicStatus.IS_DELETE.NORMAL.getId());
			result = orderContractDao.reuploadContract(contract);
		}else{
			// 插入合同记录
			OrderContractEntity  contract = new OrderContractEntity();
			contract.setOrderCode((String)param.get("orderCode"));
			contract.setFilePath((String)param.get("contractImagePath"));
			contract.setConfirmStatus(OrderConstants.ORDER_CONTRACT_STATUS.NOT_CONFIRM.getCode());
			contract.setIntro((String)param.get("intro"));
			contract.setCreater((String)param.get("creater"));
			contract.setIsDelete(PublicStatus.IS_DELETE.NORMAL.getId());
			long contractId = orderContractDao.insert(contract);
			result = (int)contractId;
		}
		
		
		param.put("orderStatus", OrderConstants.ORDER_STATUS.WAIT_TO_APPROVE.getCode());
		result += orderDao.updateOrderStatus(param);

		//记录日志
		if (param.containsKey("orderLogEntity") && param.get("orderLogEntity") != null) {
			OrderLogEntity orderLog = (OrderLogEntity)param.get("orderLogEntity");
			orderLogDao.saveOrderLog(orderLog);
		}
		// 更新订单状态 
		return result;
	}
	
	
	/**
	 * 查询个人订单状态统计数量
	 * @param param
	 * @return
	 * @author llp
	 */
	public OrderEntity listOrderStatusCount(Map<String, Object> param){
		return orderDao.listOrderStatusCount(param);
	}

	/**
	 * 确认核销订单
	 * @param param
	 * @return
	 * @author xkl
	 * @date 2017年12月23日 上午10:43:33
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor=Exception.class)
	public Integer confirmVerifyOrder(Map<String, Object> param) {
		int result1 = 0;
		try {
			String orderCode = (String)param.get("orderCode");
			int result = orderDao.confirmVerifyOrder(param);
			String approveResult = (String)param.get("approveResult");
			result1 = result - 1;
			// 核销通过，确认凭证
			if(OrderConstants.ORDER_APPROVE_STATUS.PASS.getCode().equals(approveResult)){
				param.put("confirmStatus", OrderConstants.ORDER_PAY_CONFIRM_STATUS.CONFIRMED.getCode());
				// 发放商品赠送的积分
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("orderCode", param.get("orderCode"));
				OrderEntity order = orderDao.getBy(paramMap);
				// 查询订单详情
				List<OrderDetailEntity>  detailList = orderDetailDao.listOrderDetail(paramMap);
				handleCouponPoints(order, detailList);
				// 处理客户订单推荐积分和奖金返现(货到付款的订单在核销时返现推荐人的奖励和积分)
				handleReferrerPointsAndRewards(order, detailList);
			}else{
				param.put("confirmStatus", OrderConstants.ORDER_PAY_CONFIRM_STATUS.CONFIRMED_NOT_PASS.getCode());
			}
			result1 = orderPayDao.updateOrderPayStatus(param);
			// 修改订单状态为已完成
			param.clear();
			param.put("orderCode", orderCode);
			param.put("orderStatus", OrderConstants.ORDER_STATUS.FINISHED.getCode());
			param.put("finishTime", new Date());
			orderDao.updateOrderStatus(param);

			//记录日志
			if (param.containsKey("orderLogEntity") && param.get("orderLogEntity") != null) {				
				OrderLogEntity orderLog = (OrderLogEntity)param.get("orderLogEntity");
				orderLogDao.saveOrderLog(orderLog);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new BizException("订单审核失败！");
		}
		return result1;
	}

	/**
	 * 查询订单数据
	 * @param paramMap
	 * @return
	 * @author xkl
	 * @date 2018年1月2日 下午4:34:24
	 */
	@Override
	public Map<String, Object> queryOrderData(Map<String, Object> paramMap) {
		return orderDao.queryOrderData(paramMap);
	}

	/**
	 * 查询待付款、待审核、待发货、代签收4种状态订单数量
	 * @return
	 * @author xkl
	 * @date 2018年1月2日 下午4:56:48
	 */
	@Override
	public Map<String, Object> queryOrderStatusSum() {
		return orderDao.queryOrderStatusSum();
	}
	
	/**
	 * 根据状态获取订单数量<br>
	 * （如果参数为空，则返回所有订单数量）
	 * 
	 * @param orderStatus
	 * @return int
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2018年1月2日 上午11:53:11
	 */
	public int getOrderCount(String orderStatus) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("orderStatus", orderStatus);
		return orderDao.getOrderCount(paramMap);
	}

	/**
	 * 查询订单数据列表
	 * @param paramMap
	 * @return
	 * @author xkl
	 * @date 2018年1月5日 下午3:27:16
	 */
	@Override
	public List<Object> queryOrderDataList(Map<String, Object> paramMap) {
		return orderDao.queryOrderDataList(paramMap);
	}

	/**
	 * 结束过期订单
	 * @param paramMap
	 * @return
	 * @author xkl
	 * @date 2018年1月6日 下午4:49:06
	 */
	@Override
	public Integer closeExpiredOrder(Map<String, Object> paramMap) {
		return orderDao.closeExpiredOrder(paramMap);
	}

	/**
	 * 保存交易流水
	 * @param paramMap
	 * @return
	 * @author xkl
	 * @date 2018年1月23日 下午2:26:46
	 */
	@Override
	public int saveOrderTrade(Map<String, Object> paramMap) {
		return orderDao.saveOrderTrade(paramMap);
	}

	/**
	 * 根据交易流水号获取订单号
	 * @param outTradeNo
	 * @return
	 * @author xkl
	 * @date 2018年1月23日 下午2:27:35
	 */
	@Override
	public String getOrderCodeByOutTradeNo(String outTradeNo) {
		return orderDao.getOrderCodeByOutTradeNo(outTradeNo);
	}
	
	/**
	 * 查询业务员订单数量
	 * @param paramMap
	 * @return
	 * @author xkl
	 * @date 2018年2月12日 下午4:05:39
	 */
	public Integer countSalesmanOrderSum(Map<String, Object> paramMap){
		return orderDao.countSalesmanOrderSum(paramMap);
	}

	/**
	 * 根据id集合查询用户订单统计信息
	 * @param paramMap
	 * @return
	 * @author xkl
	 * @date 2018年5月16日 下午2:48:01
	 */
	@Override
	public Map<Long, Map<String, Object>> listUsersCustomerOrderInfo(Map<String, Object> paramMap) {
		return orderDao.listUsersCustomerOrderInfo(paramMap);
	}

	/**
	 * 自动签收订单
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED ,rollbackFor = Exception.class)
	public int autoSign(Map<String, Object> paramMap) {
		String creater = "定时任务";
		try {
			// 已支付，待签收的订单进行自动签收
			paramMap.put("orderStatus", OrderConstants.ORDER_STATUS.WAIT_TO_RECEIVE.getCode());
			paramMap.put("payStatus", OrderConstants.ORDER_PAY_STATUS.PAYED.getCode());
			List<OrderEntity> orderList = orderDao.listBy(paramMap);
			if(orderList != null && orderList.size() >0){
				for (OrderEntity order : orderList) {
					Map<String, Object> param = new HashMap<String, Object>();
					param.put("orderCode", order.getOrderCode());
					param.put("creater", creater);
					//记录日志
					OrderLogEntity orderLog = new OrderLogEntity();
					orderLog.setOrderCode(order.getOrderCode());
					orderLog.setOperaterCode(creater);
					orderLog.setOperaterName(creater);
					orderLog.setOpTime(new Date());
					orderLog.setLogContent("系统自动签收");
					orderLog.setCreater(creater);
					param.put("orderLogEntity", orderLog);
					signFullOrder(param);
				}
			}
		} catch (Exception e) {
			Log.error("订单自动签收任务失败", e.getLocalizedMessage());
			throw new BizException("订单自动签收任务失败");
		}
		return 1;
	}
	
	/**
	 * 查询订单数量及金额统计
	 * @param paramMap
	 * @return
	 */
	public OrderStatisticsEntity selectOrderStatistics(Map<String, Object> paramMap){
		return orderDao.selectOrderStatistics(paramMap);
	}
}
